var express = require('express');
const bodyParser = require('body-parser');
const WebSocket = require('ws');
const gcore = require('./gcore.js');

var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static(__dirname))

app.get('/hi', function (req, res) {
   res.send('Hello World');
});


var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})

let project = new gcore.Project();


var wss  = new WebSocket.Server({server})

let that = this;
wss.on('connection',function connection(ws,req){
     const ip = req.socket.remoteAddress
     const port = req.socket.remotePort
     const clientName = ip +":"+ port
     console.log('%s:%s is connected ',ip,port);
     project.addPlayer(clientName,ws);
     ws.send("haha");
     ws.on('message',function incoming(message){
       messageHandle(clientName,message);
     });
     ws.on('close',function close(message){
       closeHandle(clientName,message);
     });
     ws.on('error',function error(message){
       errorHandle(clientName,message);
     });

});
//     ws.on('close',fu


function messageHandle(cname , message){
  project.rmsg(cname,message);
}

function closeHandle(cname,msg){
  console.log("close ",cname , msg)
  project.removePlayer(cname);
}

function errorHandle(cname , msg){
  console.log("error " , cname,msg)
}







app.post('/createRoome',function(req,res){
  project.createRoome(nick,roomName);
  res.send("success");
});

app.post('/getRooms',function (req , res){
  console.log(JSON.stringify(req.body));
  var rooms = project.getRooms();
  res.send('{"name":"first Roome"}');
});


app.post('/joinRoom',function(req,res){
  project.joinRoom(nick,room);
});

app.post('/leaveRoom',function(req,res){
  project.leaveRoom(nick,Room);
});










